/* eslint-disable */
/**
 * storage
 * 缓存封装
 * localStorage,
 * sessionStorage
 */

// sessionStorage
const getItem = (key: string) => {
  if (!key && !window.sessionStorage) return null;

  key = key.toString();
  const data = window.sessionStorage.getItem(key);
  if (data) {
    return JSON.parse(data);
  }
  return undefined;
};

// 存储
const setItem = (key: string, value) => {
  if (!key && !window.sessionStorage) return null;
  try {
    key = key.toString();

    if (typeof value === 'string') {
      window.sessionStorage.setItem(key, value);
      return value;
    } else {
      window.sessionStorage.setItem(key, JSON.stringify(value));
      return value;
    }
  } catch (e) {
    return null;
  }
};

// 删除
const removeItem = (key) => {
  if (!key && !window.sessionStorage) return null;
  try {
    key = key.toString();

    window.sessionStorage.removeItem(key);
  } catch (e) {
    return null;
  }
};

// 删除所有
// eslint-disable-next-line consistent-return
const clearItem = () => {
  if (!window.sessionStorage) return null;
  try {
    window.sessionStorage.clear();
  } catch (e) {
    return null;
  }
};

// localStorage
const getLocal = (key: string) => {
  if (!key && !window.localStorage) return null;

  key = key.toString();
  const data = window.localStorage.getItem(key);
  if (data) {
    return JSON.parse(data);
  }
  return undefined;
};
// 存储
const setLocal = (key, value) => {
  if (!key && !window.localStorage) return null;
  try {
    key = key.toString();

    if (typeof value === 'string') {
      window.localStorage.setItem(key, value);
      return value;
    } else {
      window.localStorage.setItem(key, JSON.stringify(value));
      return value;
    }
  } catch (e) {
    return null;
  }
};
// 删除
const removeLocal = (key) => {
  if (!key && !window.localStorage) return null;
  try {
    key = key.toString();

    window.localStorage.removeItem(key);
  } catch (e) {
    return null;
  }
};
// 删除所有
// eslint-disable-next-line consistent-return
const clearLocal = () => {
  if (!window.localStorage) return null;
  try {
    window.localStorage.clear();
  } catch (e) {
    return null;
  }
};
export default {
  getItem,
  setItem,
  removeItem,
  clearItem,
  getLocal,
  setLocal,
  removeLocal,
  clearLocal,
};
